<?php

namespace common\jobs\handle;

use Yii;
use yii\db\Exception;
use common\models\shop\ShopOrder;
use common\models\user\UserBranch;
use common\models\member\MemberMarketLog;
use common\models\member\MemberAccount;
use common\models\member\MemberAccountLog;
use common\helpers\IpHelper;

/**
 * 订单返佣任务处理
 *
 * @author emhome <emhome@163.com>
 * @since 1.0
 */
class RakeBackHandle extends \common\jobs\base\BaseJobHandleModel {

    /**
     * @var integer 订单ID
     */
    public $order_id = null;

    /**
     * @var ShopOrder|null 商城订单
     */
    public $_model = null;

    /**
     * {@inheritdoc}
     */
    public function rules() {
        return [
            [['order_id'], 'required'],
            [['order_id'], 'integer'],
            [['order_id'], 'validateOrder'],
        ];
    }

    /**
     * 校验订单信息
     * @param string $attribute the attribute currently being validated
     */
    public function validateOrder($attribute) {
        if ($this->hasErrors()) {
            return;
        }
        $model = ShopOrder::findOne($this->$attribute);
        if (!$model) {
            return $this->addError($attribute, '【' . $this->$attribute . '】订单不存在！');
        }
        if ($model->hasRakeBack()) {
            return $this->addError($attribute, '【' . $this->$attribute . '】订单已返佣！');
        }
        $this->_model = $model;
    }

    /**
     * 获取订单信息
     * @return ShopOrder|null
     */
    public function getModel() {
        return $this->_model;
    }

    /**
     * 执行返佣
     * @inheritdoc
     */
    public function save() {
        if (!$this->validate()) {
            return $this->dumpError('返佣操作失败');
        }
        //获取订单信息
        $order = $this->getModel();
        //获取订单用户的分销会员，如存在则继续，不存在返回
        $member = UserBranch::findMemberByUserId($order->user_id);
        if (!$member) {
            return $this->dumpSuccess('【' . $this->order_id . '】无需返佣。');
        }
        $account = $member->account;
        if (!$account) {
            $account = new MemberAccount();
            $account->attributes = [
                'user_id' => $member->user_id,
                'member_id' => $member->id,
                'amount' => 0,
                'current' => 0,
                'status' => MemberAccount::STATUS_ACTIVE,
            ];
        }
        //检测会员用户是否和订单用户一致
        $price = 0;
        //涉及到付钱就涨经验
        $experience = intval($order->pay * 100);
        //分销会员订单时获得佣金提成
        if ($member->user_id != $order->user_id) {
            $_price = (1 - $member->scale) * $order->pay * 100;
            $price = round($_price);
        }
        //创建成功分销订单
        $marketLog = new MemberMarketLog();
        $marketLog->attributes = [
            'user_id' => $member->user_id,
            'member_id' => $member->id,
            'model' => 'ShopOrder',
            'model_id' => $order->id,
            'model_user_id' => $order->user_id,
            'price' => $price,
            'experience' => $experience,
            'status' => MemberMarketLog::STATUS_ACTIVE,
        ];
        $accountLog = null;
        //佣金入账
        if ($price > 0) {
            $account->amount += $price;
            $account->current += $price;
            //记录账户佣金变动日志
            $accountLog = new MemberAccountLog();
            $accountLog->attributes = [
                'user_id' => $member->user_id,
                //'account_id' => '会员账户ID',
                'balance' => MemberAccountLog::BALANCE_IN,
                'value' => $price,
                'recharge' => 0,
                'from_user_id' => $order->user_id,
                'trade_id' => $order->trade_id,
                'ip' => IpHelper::ip(),
                'status' => MemberAccountLog::STATUS_ACTIVE,
            ];
        }
        //增加经验
        if ($experience > 0) {
            $member->experience += $experience;
        }
        //开启事务保存
        $transaction = Yii::$app->db->beginTransaction();
        try {
            if (!$marketLog->save()) {
                throw new Exception('分销订单保存失败！');
            }
            if (!$member->save()) {
                throw new Exception('会员经验更新失败！');
            }
            if (!$account->save()) {
                throw new Exception('入账失败！');
            }
            if ($accountLog !== null) {
                $accountLog->account_id = $account->id;
                if (!$accountLog->save()) {
                    throw new Exception('账户日志增加失败！');
                }
            }
            $transaction->commit();
        } catch (Exception $e) {
            $transaction->rollBack();
            $this->dumpRetryError($e->getMessage());
        }
        return $this->dumpSuccess([
            'OrderId' => $order->id,
            'MemberId' => $member->id,
            'UserId' => $member->user_id,
            'Message' => '订单返佣成功！',
        ]);
    }

}
